import sys
import getopt
import re

def count_char(content):
    print(f"num of char:{len(content)}\n")

def count_word(content):
    m=re.findall(r"\w+",content)
    print(f"num of words:{len(m)}\n")

def count_line(line):
    print(f"num of lines:{len(line)}\n")

def count_function(content):
    m=re.sub(r"#.*\n","\n",content)
    m=re.sub(r"'''[\s\S]*'''","\n",m)
    function_list=re.findall(r"def \w+\(\):",m)
    print(f"num of functions:{len(functino_list)}")

if __name__ =="__main__":
    opts,args=getopt.getopt(sys.argv[1:],"lcwfh",["line","char","word","function","help"])
    if len(args)>1 :
        print("输入有误，一次只接受一个文件\n")
    file_name=args[0]
    with open(file_name,"r",encoding="utf-8") as file:
        for u,v in opts:
            if u in ("-l","--line"):
                count_line(file.readlines())
                file.seek(0)
            elif u in ("-c","--char"):
                count_char(file.read())
                file.seek(0)
            elif u in ("-w","--word"):
                count_word(file.read())
                file.seek(0)
            elif u in ("-f","--function"):
                count_function(file.read())
                file.seek(0)
            elif u in ("-h","--help"):
                print("源程序（python）特征统计：\n   -l/--line ： 统计行数\n   -c/--char ： 统计字符数\n   -w/--word ： 统计单词数\n   -f/--funtion ： 统计函数个数\n")
            else:
                print("无法识别关键词，也许你可以尝试-h/--help查看支持的关键词。")









